<template>
  <zeda-dialog
    v-model="visible"
    :title="(id <= 0 ? '新建' : '编辑') + ''"
    width="500px"
    :before-close="handleClose"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <form-button
      slot="footer"
      :loading="loading"
      :submitText="'确定'"
      @cancel="handleClose"
      @submit="submit"
    >
    </form-button>
  </zeda-dialog>
</template>

<script>
import { getroomDetail, addroom, editroom } from "@/api/park/roommsg.js";
import { getparkList } from "@/api/park/parkmsg.js";
import { getbuildingList } from "@/api/park/buildingmsg.js";
import { getfloorList } from "@/api/park/floormsg.js";
import { getroomTypeList } from "@/api/park/roomType.js";

import CascaderSelect from "@/components/Select/CascaderSelect";
import FormButton from "@/components/FormButton";
import {
  deepClone,
  replaceDigit,
  replaceInteger,
  dealElectricity,
} from "@/utils/index";

export default {
  dicts: ["room_direction", "special_energy_consumption_type"],
  components: {
    FormButton,
    CascaderSelect,
  },
  props: {
    id: {
      type: [Number, String],
      default: "",
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      usedDeptId: "",
      loading: false, // 按钮加载中判断
      parkList: [],
      buildingList: [],
      floorList: [],
      roomTypeList: [],
      apsForm: {
        formRef: "form",
        formData: {},
        formConfig: {
          formAttr: {
            // inline: true,
            "label-position": "right",
            size: "small",
            bsColumn: {
              col: 1,
              middle: true,
            },
            rules: {
              parkId: [
                {
                  required: true,
                  message: "请选择园区",
                  trigger: "change",
                },
              ],
              buildingId: [
                {
                  required: true,
                  message: "请选择楼宇",
                  trigger: "change",
                },
              ],
              floorId: [
                {
                  required: true,
                  message: "请选择楼层",
                  trigger: "change",
                },
              ],
              roomType: [
                {
                  required: true,
                  message: "请选择房间类型",
                  trigger: "change",
                },
              ],
              name: [
                {
                  required: true,
                  message: "请输入房间号",
                  trigger: "blur",
                },
                // {
                //   validator: function (rule, value, callback) {
                //     let reg = new RegExp(
                //       "^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$"
                //     );
                //     if (!reg.test(value)) {
                //       callback("请勿输入特殊字符，且不能以下划线开头和结尾");
                //     } else {
                //       callback();
                //     }
                //   },
                //   trigger: "blur",
                // },
              ],
              roomArea: [
                {
                  required: false,
                  message: "请输入正确的房间面积",
                  trigger: "blur",
                },
              ],
              direction: [
                {
                  required: false,
                  message: "请选择房间朝向",
                  trigger: "change",
                },
              ],
            },
          },
          properties: {
            parkId: {
              label: "园区名称",
              render: (h) => {
                let that = this;
                let arr = [...that.parkList];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().parkId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择园区",
                        value: valNum,
                        clearable: true,
                        disabled: that.disabledFlage,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("parkId", value);
                          that.$refs?.form?.setFieldValue("buildingId", null);
                          that.$refs?.form?.setFieldValue("floorId", null);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            buildingId: {
              label: "楼宇名称",
              render: (h) => {
                let that = this;
                let arr = [...that.buildingList];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().buildingId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择楼宇",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("buildingId", value);
                          that.$refs?.form?.setFieldValue("floorId", null);
                          that.$forceUpdate();
                        },
                        "visible-change": (value) => {
                          if (value) {
                            that.requestBuildinglist();
                          }
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            floorId: {
              label: "楼层名称",
              render: (h) => {
                let that = this;
                let arr = [...that.floorList];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().floorId;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "楼层名称",
                        value: valNum,
                        clearable: true,
                        filterable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("floorId", value);
                          that.$forceUpdate();
                        },
                        "visible-change": (value) => {
                          if (value) {
                            that.requestFloorList();
                          }
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            roomType: {
              label: "房间类型",
              render: (h) => {
                let that = this;
                let arr = [...that.roomTypeList];
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().roomType;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "房间类型",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("roomType", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            name: {
              label: "房间号",
              typeName: "el-input",
              maxlength: 30,
              placeholder: "请输入房间号",
            },
            nickname: {
              label: "房间名称",
              typeName: "el-input",
              maxlength: 30,
              placeholder: "请输入房间名称",
            },
            roomArea: {
              label: "房间面积",
              typeName: "el-input",
              render: (h) => {
                let that = this;
                let a = (
                  <el-input
                    placeholder="请输入房间面积"
                    clearable
                    size="small"
                    maxlength="10"
                    value={that.$refs?.form?.getFieldsValue().roomArea}
                    onInput={(val) => that.replaceDigitDeal(val, 2, "roomArea")}
                  >
                    <template slot="append">
                      <span>㎡</span>
                    </template>
                  </el-input>
                );
                return a;
              },
            },
            direction: {
              label: "房间朝向",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.room_direction.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().direction;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择房间朝向",
                        value: valNum,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("direction", value);
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            usedDeptId: {
              label: "使用部门",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                return (
                  <div>
                    <CascaderSelect
                      value={that.usedDeptId}
                      values={that.usedDeptId}
                      varient={"energy"}
                      size={"small"}
                      placeholder={"请选择"}
                      onInput={(value) => {
                        let result;
                        if (value && value.length > 0) {
                          result = value[value.length - 1];
                        } else {
                          result = null;
                        }
                        that.$refs?.form?.setFieldValue("usedDeptId", result);
                      }}
                    ></CascaderSelect>
                  </div>
                );
              },
            },
            specialEnergyFlag: {
              label: "用能类型",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.special_energy_consumption_type.some(
                  (item) => {
                    arr.push(item);
                  }
                );
                // 数据严谨处理,处理后端数据异常情况
                let valNum =
                  that.$refs?.form?.getFieldsValue().specialEnergyFlag;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择用能类型",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue(
                            "specialEnergyFlag",
                            value
                          );
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
            shared: {
              label: "是否公摊",
              render: (h) => {
                let that = this;
                let a = (
                  <el-radio-group
                    value={that.$refs?.form?.getFieldsValue().shared}
                    onChange={(value) => {
                      let val = value == 0 ? 1 : 0;
                      that.$refs?.form?.setFieldValue("shared", val);
                    }}
                  >
                    <el-radio label={1}>是</el-radio>
                    <el-radio label={0}>否</el-radio>
                  </el-radio-group>
                );
                return a;
              },
            },
            remarks: {
              label: "备注",
              typeName: "el-input",
              type: "textarea",
              rows: 4,
              maxlength: 200,
              placeholder: "请输入备注",
            },
          },
        },
      },
    };
  },
  watch: {
    visible: {
      handler(value) {
        if (value) {
          this.requestParklist();
          this.requestBuildinglist();
          this.requestFloorList();
          this.requestroomTypelist();

          if (String(this.id).length > 0) {
            setTimeout(() => {
              this.getInfo();
            }, 200);
          }
        }
      },
      deep: false,
      immediate: false,
    },
  },
  methods: {
    // 园区集合
    requestParklist() {
      this.parkList = [];
      getparkList({})
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.rows ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let obj = {
                label: item?.name ?? "",
                value: item?.id,
              };
              this.parkList.push(obj);
            });
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!401001");
        });
    },
    // 楼宇集合
    requestBuildinglist() {
      this.buildingList = [];
      let params = {};
      let parkId = this.$refs?.form?.getFieldsValue().parkId;
      if (String(parkId).length > 0) {
        params.parkId = parkId;
      }
      getbuildingList(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.rows ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let obj = {
                label: item?.name ?? "",
                value: item?.id,
              };
              this.buildingList.push(obj);
            });
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!402001");
        });
    },
    // 楼层集合
    requestFloorList() {
      this.floorList = [];
      let params = {};
      let parkId = this.$refs?.form?.getFieldsValue().parkId;
      let buildingId = this.$refs?.form?.getFieldsValue().buildingId;
      if (String(parkId).length > 0) {
        params.parkId = parkId;
      }
      if (String(buildingId).length > 0) {
        params.buildingId = buildingId;
      }
      getfloorList(params)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.rows ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let obj = {
                label: item?.name ?? "",
                value: item?.id,
              };
              this.floorList.push(obj);
            });
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!403001");
        });
    },
    // 房间类型
    requestroomTypelist() {
      this.roomTypeList = [];
      getroomTypeList({})
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let arr = res?.rows ?? [];
          if (arr.length > 0) {
            arr.map((item) => {
              let obj = {
                label: item?.name ?? "",
                value: item?.id,
              };
              this.roomTypeList.push(obj);
              this.$refs?.form?.setFieldValue("shared", 0);
            });
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!304001");
        });
    },
    getInfo() {
      getroomDetail(this.id)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          let newData = res?.data || {};
          newData.roomArea = dealElectricity(
            res?.data?.roomArea ?? 0,
            100,
            2,
            "number"
          );
          this.$refs?.form?.setFieldsValue(newData);
          this.usedDeptId = newData.usedDeptId;
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!404004");
        });
    },
    submit() {
      const data = {
        ...this.$refs.form.getFieldsValue(),
      };
      data.roomArea = Number(data?.roomArea ?? 0) * 100;
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.id) {
            this.editRequest(data);
          } else {
            this.addRequest(data);
          }
        } else {
          return false;
        }
      });
    },
    addRequest(data) {
      addroom(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!404002");
        });
    },
    editRequest(data) {
      editroom(data)
        .then((res) => {
          this.loading = false;
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.$message.success("操作成功");
          this.handleClose(true);
        })
        .catch(() => {
          this.loading = false;
          // this.$message.error("系统错误,请联系管理员!404003");
        });
    },
    handleClose(status) {
      this.$refs["form"].resetFields();
      this.usedDeptId = "";
      this.$emit("update:visible", false);
      this.$emit("close", status === true ? status : false);
    },
    /* 输入限制 */
    // 限制输入保留小数位数
    replaceDigitDeal(val, dit, flage) {
      let result = replaceDigit(val, dit);
      this.$refs?.form?.setFieldValue(flage, result);
    },
    // 限制输入整数
    replaceIntegerDeal(val, flage) {
      let result = replaceInteger(val);
      this.$refs?.form?.setFieldValue(flage, result);
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .el-form {
  .el-input,
  .el-cascader,
  .el-input-number,
  .el-select {
    width: 100% !important;
  }
  .map {
    display: flex;
    .el-input {
      margin-right: 10px;
    }
  }
}
</style>
